<?php
/**
 * Copyright (C) 2021 Tencent Cloud.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace App\Api\Controller\Plugin;

use App\Common\PermissionKey;
use App\Common\Utils;
use App\Models\PluginGroupPermission;
use App\Repositories\UserRepository;
use Discuz\Base\DzqController;

class PluginListController extends DzqController
{
    protected function checkRequestPermissions(UserRepository $userRepo)
    {
        return parent::checkRequestPermissions($userRepo); // TODO: Change the autogenerated stub
    }

    public function main()
    {
        $pluginList = \Discuz\Common\Utils::getPluginList();
        $permissions = PluginGroupPermission::query()
            ->where('group_id', $this->user->groupId)->get()->keyBy('app_id')->toArray();
        $isAdmin = $this->user->isAdmin();
        foreach ($pluginList as &$item) {
            $permission = $permissions[$item['app_id']] ?? null;
            $appId = $item['app_id'];
            $appName = $item['name_en'];
            $pluginDirectories = $item['plugin_' . $appId];
            //当前登录用户权限
            $item['authority'] = [
                'title' => '插入' . $item['name_cn'],
                'permission' => PermissionKey::PLUGIN_INSERT_PERMISSION,
                'canUsePlugin' => $isAdmin ? true : (empty($permission) ? false : ($permission['status'] ? true : false)),
            ];
            $distPath = $pluginDirectories['view'].'/dist';
            $pluginFiles = [];
            if(file_exists($distPath)){
                $distFiles = scandir($distPath);
                foreach ($distFiles as $distFile) {
                    if ($distFile == '.' || $distFile == '..') continue;
                    $pluginFiles[] =Utils::getDzqDomain() . "/plugin/{$appName}/{$distFile}";
                }
            }
            //前端插件入口
            $item['plugin_files'] = $pluginFiles;
            unset($item['plugin_' . $appId]);
            unset($item['busi']);
        }
        $this->outPut(0, '', array_values($pluginList));
    }
}
